<template>
  <div class="container">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <van-search
    v-model.trim="searchText"
    placeholder="请输入搜索关键词"
    @search="onSearch(searchText)"
    ></van-search>
    <van-cell-group v-if="suggestionList.length>0">
      <van-cell
      icon="search"
      v-for="(item,k) in suggestionList"
      :key="k"
      @click="onSearch(item)"
      >
      <div slot="title" v-html="highLightCell(item,searchText)"></div>
      </van-cell>
    </van-cell-group>
    <van-cell-group v-else>
  <van-cell title="历史记录">
    <van-icon
              @click="isDeleteData=true"
              v-show="!isDeleteData"
              slot="right-icon"
              name="delete"
              style="line-height:inherit"
              ></van-icon>
    <div v-show="isDeleteData">
      <span style="margin-right:10px" @click="suggestDelAll()">全部删除</span>
      <span @click="isDeleteData=false">完成</span>
    </div>
  </van-cell>
  <van-cell :title="item" v-for="(item,k) in suggestHistories" :key="k">
    <van-icon v-show="isDeleteData" slot="right-icon" name="close" style="line-height:inherit" @click="suggestDel(k)"></van-icon>
  </van-cell>
</van-cell-group>
  </div>
</template>

<script>
import { apiSearchSuggestion } from '@/api/search'
const SH = 'suggest-histories'
export default {
  name: 'search-index',
  data () {
    return {
      suggestHistories: JSON.parse(localStorage.getItem(SH) || '[]'),
      searchText: '',
      suggestionList: [],
      isDeleteData: false
    }
  },
  methods: {
    suggestDelAll () {
      this.suggestHistories = []
      localStorage.removeItem(SH)
    },
    suggestDel (index) {
      this.suggestHistories.splice(index, 1)
      localStorage.setItem(SH, JSON.stringify(this.suggestHistories))
    },
    onSearch (keywords) {
      if (!keywords) {
        return false
      }
      const st = new Set(this.suggestHistories)
      st.add(keywords)
      this.suggestHistories = Array.from(st)
      localStorage.setItem(SH, JSON.stringify(this.suggestHistories))
      this.$router.push({ name: 'result', params: { q: keywords } })
    },
    highLightCell (content, keywords) {
      const reg = new RegExp(keywords, 'i')
      const rst = content.match(reg)
      if (rst === null) {
        return content
      }
      return content.replace(reg, `<span style="color:red;">${rst[0]}</span>`)
    }
  },
  watch: {
    searchText: function (newV) {
      clearTimeout(this.timer)
      if (!newV) {
        this.suggestionList = []
        return false
      }
      this.timer = setTimeout(async () => {
        const result = await apiSearchSuggestion(newV)
        this.suggestionList = result.options
      }, 1000)
    }
  }
}
</script>

<style scoped lang='less'></style>
